/**
 * 悬赏任务 - CheckVersion
 * http://menger.me
 * @大梦
 */

'use strict';

import React from 'react'
import {Linking, StyleSheet, Text, View,} from 'react-native'
import {Predefine} from '../config/predefine'
import Constants from '../config/constant/Customer'
import {AlertManager, ToastManager} from '../components'
import {ServerApi as ServicesApi, ServerCode as StatusCode} from '../services'

/**
 * 提交当前版本
 * Author: 梦
 * Date: 2019/01/10
 * Return: 版本信息
 */
const checkVersion = (showToast = true, showLoading = true, onCallBack = () => {}, isModal = true) => {
    let url = ServicesApi.VERSION_INFO;
    let data = {
        platform: __IOS__,
        version_code: Constants.VERSION_CODE,
        version_name: Constants.VERSION_NAME,
    };
    showLoading && ToastManager.loading('检查更新中...');
    Services.post(url, data)
        .then((result) => {
            onCallBack(result);
            global.PG_SUCCESS = result.data.ios_online;
            setTimeout(() => {
                showToast && ToastManager.hide();
                if (result.code === StatusCode.SUCCESS_CODE && result.data.new_version > 0) {
                    showVersionPopupView(isModal, result.data.version);
                } else {
                    showToast && ToastManager.message('当前已是新版本！');
                }
            }, 1000);
        })
        .catch((error) => {
            console.log('error---->', error);
        })
};

/**
 * 新版本弹窗
 * Author: 梦
 * Date: 2019/01/10
 */
const showVersionPopupView = (isModal = true, data) => {
    let {title, version_code, content, link_ios_shipper, link_android_shipper} = data;
    let link = __IOS__ ? link_ios_shipper : link_android_shipper;
    let detail = content.map((item, index) => {
        return (
            <Text key={item.id} style={styles.alertItemStyle}>{index + 1}、{item.value}</Text>
        );
    });
    let detailContent = (
        <View style={styles.alertContent}>
            <View style={styles.versionContent}>
                <Text style={styles.versionStyle}>{version_code}</Text>
            </View>
            <View style={styles.detailContentStyle}>
                <Text style={styles.detailContentTitle}>{title}</Text>
                {detail}
            </View>
        </View>
    );
    const params = {
        title: '发现新版本',
        style: {width: Predefine.screenWidth - 40,},
        detail: detailContent,
        actions: [
            {
                title: '立即升级',
                onPress: () => submitUpdate(link),
            }
        ],
        actionContainerStyle: {width: Predefine.screenWidth - 50},
        option: {
            modal: isModal,
        }
    };
    AlertManager.show(params);
};

/**
 * 跳转下载页面
 * Author: 梦
 * Date: 2019/01/10
 */
const submitUpdate = (url) => {
    Linking.canOpenURL(url)
        .then(supported => {
            if (!supported) {
                ToastManager.show('无法打开该链接');
                return;
            } else {
                return (
                    Linking.openURL(url)
                        .catch(e => {
                            console.log('e---->', e);
                            ToastManager.show('打开链接出错，请稍后重试');
                        })
                );
            }
        })
        .catch(error => {
            console.log('error---->', error);
            ToastManager.show('打开链接出错，请稍后重试');
        });
};

const styles = StyleSheet.create({
    alertContent: {
        paddingTop: 10,
        paddingBottom: 10,
        justifyContent: 'flex-start',
        width: Predefine.screenWidth - 100,
        maxWidth: Predefine.screenWidth - 100,
    },
    versionContent: {
        marginBottom: 15,
        paddingBottom: 15,
        borderColor: '#333',
        alignItems: 'center',
        borderBottomWidth: Predefine.minPixel,
    },
    versionStyle: {
        color: '#fff',
        borderRadius: 12,
        paddingVertical: 3,
        overflow: 'hidden',
        paddingHorizontal: 15,
        backgroundColor: Predefine.themeColor,
    },
    detailContentStyle: {
        minHeight: 80,
        paddingHorizontal: 15,
    },
    detailContentTitle: {
        fontSize: 14,
        color: '#333',
        lineHeight: 20,
        marginBottom: 5,
        fontWeight: '600',
        fontFamily: 'PingFangSC-Regular'
    },
    alertItemStyle: {
        fontSize: 12,
        color: '#333',
        lineHeight: 20,
        fontFamily: 'PingFangSC-Regular',
    },
});

export default checkVersion;